/**
 * 设置PLC参数
 * @author xiaoxujs
 */

import { Form, Input, InputNumber, message, Modal } from "antd";
import { FC, useEffect, useState } from "react";
import { IYckzZyLoadControlParamSet, IYckzZyLoadControlParamSetSetPlcVO } from "../../../../../type/remoteControl/loadingControlList";
import { postYckzZyLoadControlPlcParamSet } from "../../../api";

const SetPlcModule: FC<{
  open: boolean,
  handleSetPlcCallback: () => void;
  clickData?: IYckzZyLoadControlParamSet,
  clickId?: string;
}> = ({
  open,
  handleSetPlcCallback,
  clickData,
  clickId
}) => {

    const [form] = Form.useForm<IYckzZyLoadControlParamSetSetPlcVO>();

    const [loading, setLoading] = useState(false);

    useEffect(() => {
      if (clickData) {
        form.setFieldsValue(clickData.setPlcVO)
      }
    }, [clickData, form])
    const handleOk = async () => {
      const values = await form.validateFields();
      if (clickData && clickId) {
        setLoading(true);
        const { code, msg } = await postYckzZyLoadControlPlcParamSet({
          ...values,
          plcId: clickData.setPlcVO.plcId,
          id: clickId
        }) as { code: number; msg: string };
        if (code === 20000) {
          form.resetFields();
          handleSetPlcCallback();
        } else {
          message.error(msg)
        }
        setLoading(false)

      }

    };

    const handleCancel = () => {
      handleSetPlcCallback();
    };
    return <Modal title="设置PLC参数" confirmLoading={loading} open={open} onOk={handleOk} onCancel={handleCancel}>
      <Form
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 14 }}
        form={form}
      >
        <Form.Item<IYckzZyLoadControlParamSetSetPlcVO>
          label="IP地址"
          name="plcIp"
          rules={[{ required: true, message: '请输入IP地址!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item<IYckzZyLoadControlParamSetSetPlcVO>
          label="端口号"
          name="plcPort"
          rules={[{ required: true, message: '请输入端口号!' }]}
        >
          <InputNumber style={{ width: '100%' }} min={0} max={65535}  />
        </Form.Item>
        <Form.Item<IYckzZyLoadControlParamSetSetPlcVO>
          label="连接超时时间(毫秒)"
          name="plcConnectTime"
          rules={[{ required: true, message: '请输入连接超时时间!' }]}
        >
          <InputNumber style={{ width: '100%' }} min={0} max={500}/>
        </Form.Item>
        <Form.Item<IYckzZyLoadControlParamSetSetPlcVO>
          label="读写超时时间(毫秒)"
          name="plcReadTime"
          rules={[{ required: true, message: '请输入连接超时时间!' }]}
        >
          <InputNumber style={{ width: '100%' }} min={0} max={500} />
        </Form.Item>
      </Form>
    </Modal>
  }

export default SetPlcModule;